<template>
  <div>
    <NavTop style="position: fixed;left:0;top:0;z-index: 999;">
      <BackBtn />
      <div class="navtop-title">{{ $route.params.type }}</div>
    </NavTop>
    <div class="content">
      <van-form @submit="onSubmit">
        <!-- 群头像上传 -->
        <van-field name="uploader" label="群头像">
          <template #input>
            <van-uploader
              v-model="groupInfo.fileList"
              multiple
              accept="image/*"
              :max-count="1"
              :before-read="beforeRead"
              :after-read="afterRead"
            />
          </template>
        </van-field>
        <!-- 群昵称 -->
        <van-field
          v-model="groupInfo.groupName"
          name="groupName"
          label="群昵称"
          placeholder="请设置群昵称"
          :rules="[{ required: true }]"
          autocomplete="off"
          maxlength="15"
        />
        <!-- 群简介 -->
        <van-field
          v-model="groupInfo.sign"
          name="sign"
          rows="2"
          autosize
          label="群简介"
          type="textarea"
          maxlength="50"
          placeholder="请输入群简介"
          show-word-limit
        />
        <div  class="bottom-btn">
          <van-button round block type="info" native-type="submit"
            >保存</van-button
          >
        </div>
      </van-form>
      <!-- 群成员列表 -->
      <div class="group-user-content" v-if="this.$route.params.type === '编辑群聊'">
        <div class="content-title">群成员管理({{ groupUserList.length }}人)</div>
        <ul>
            <li v-for="(item,index) in groupUserList" :key="index">
                <div class="user-pic">
                    <img :src="$baseUrl + item.userId.imgUrl" alt="">
                </div>
                <div class="user-nick">{{ item.userId.nick }}</div>
                <van-icon name="delete-o" class="del-user" @click="delGroupUser(item.userId._id, index)"/>
            </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import NavTop from "@/components/NavTop"
import BackBtn from "@/components/BackBtn"
import { reqCreateGroup, reqGroupPic, reqGetUpdateGroupInfo, reqUpdateGroupInfo, reqDelGroupUser } from '@/api'
import { mapState } from "vuex"
import { Toast, Dialog } from "vant"
export default {
  components: {
    NavTop,
    BackBtn
  },
  data() {
    return {
      groupInfo: {
        groupName: "",
        sign: "",
        fileList: []
      },
      groupImgUrl: '',
      groupUserList: []
    }
  },
  computed: {
    ...mapState({
        userId: state => state.login.userInfo._id
    })
  },
  methods: {
    // 保存按钮
    async onSubmit(values) {
      const { groupName, sign } = values
      /**
       * 参数：
       *    userId: 群主id
            groupName: 群名称
            groupNumber: 群号(后端生成)
            sign: 群简介
            imgUrl: 群头像
            creatTime: 创建时间(后端生成)
       */
      if (this.$route.params.type === '新建群聊') {
        // 新建群聊
        const file = values.uploader.length ? values.uploader[0].file : ''
        let info = {
          userId: this.userId,
          groupName,
          sign,
          imgUrl: file ? this.groupImgUrl : '/group_pic.png'
        }
        let res = await reqCreateGroup(info)
        Toast(res.msg)
        setTimeout(() => {
          this.$router.push('/message')
        }, 1000)
      } else {
        // 编辑群聊
        let info = {
          _id: this.$route.query._id,
          groupName,
          sign,
          imgUrl: values.uploader.length ? this.groupImgUrl : '/group_pic.png'
        }
        let res = await reqUpdateGroupInfo(info)
        Toast(res.msg)
      }
    },
    // 上传图片类型（返回布尔值）
    beforeRead(file) {
      if (file.type === "image/png" || file.type === "image/jpeg" || file.type === "image/jpg") {
        return true
      }
      Toast("请上传 jpg、png 或 jpeg 格式图片")
      return false
    },
    // 图片上传后
    async afterRead(file) {
        file.status = 'uploading'
        file.message = '上传中...'
        let form = new FormData()
        form.append('file', file.file)
        try {
            let res = await reqGroupPic(form)
            if (res.res_code === '0') {
                file.status = 'done'
                file.message = '上传成功'
                this.groupImgUrl = res.url
                Toast('头像上传成功')
            } else {
                file.status = 'failed'
                file.message = '上传失败'
            }
        } catch (error) {
            file.status = 'failed'
            file.message = '上传失败'
        }
    },
    // 编辑群聊（获取当前需要编辑群聊的信息）
    async getUpdateGroupInfo() {
      let groupId = this.$route.query._id
      let groupLeaderId = this.$route.query.leaderId
      let res = await reqGetUpdateGroupInfo({groupId, groupLeaderId})
      if (res.status === 200) {
        // 群信息
        const { groupName, imgUrl, sign } = res.data.groupInfo
        this.groupInfo.groupName = groupName
        this.groupInfo.imgUrl = imgUrl
        this.groupInfo.sign = sign
        this.groupInfo.fileList.push({
          url: this.$baseUrl + imgUrl
        })
        this.groupImgUrl = imgUrl
        // 群成员列表
        this.groupUserList = res.data.groupUserList
      }
    },
    // 删除群成员
    delGroupUser(id, index) {
      Dialog.confirm({
        message: '你确定要将ta移除群聊吗?'
      })
      .then(async() => {
        // 确定
        let ids = {
          userId: id,
          groupId: this.$route.query._id
        }
        let res = await reqDelGroupUser(ids)
        if (res.status === 200) {
          this.groupUserList.splice(index, 1)
        }
        Toast(res.msg)
      })
      .catch(() => {
        // 取消
      })
    }
  },
  mounted() {
    if (this.$route.params.type === '编辑群聊') {
      this.getUpdateGroupInfo()
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  padding-top: 1.3333rem;
}
.bottom-btn {
  width: 100%;
  padding: .2rem .2rem;
  box-sizing: border-box;
  position: fixed;
  left: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 999;
}
.group-user-content {
  width: 100%;
  padding: .4rem;
  box-sizing: border-box;
  padding-bottom: 1.6rem;
  .content-title {
    font-size: .3733rem;
    color: #646566;
    margin-bottom: 0.4rem;
  }
  ul {
    li {
      width: 100%;
      height: 1.4667rem;
      display: flex;
      align-items: center;
      .user-pic {
          width: 1.0667rem;
          height: 1.0667rem;
          overflow: hidden;
          border-radius: 50%;
          img {
              width: 100%;
              height: 100%;
          }
      }
      .user-nick {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: .4rem;
          margin-left: .2667rem;
      }
    }
  }
}
.del-user {
  font-size: .4667rem;
}
</style>

<style>
.van-dialog__confirm, .van-dialog__confirm:active {
  color: #1989fa;
}
</style>